<template>
  <view class="content" ref="webView">
    <view class="header">
      <text class="title">智能体配置</text>
    </view>

    <view class="upload-section">
      <!-- <button class="upload-btn" @click="uploadFile">
        <text class="btn-icon">+</text>
        <text class="btn-text">上传配置文件</text>
      </button> -->
      <heyuan-chooseFile @readJSONFinish="readFile"></heyuan-chooseFile>
    </view>

    <view class="list-section">
      <view class="list-header">
        <text class="list-title">已配置智能体</text>
        <text class="list-count" v-if="urlList.length > 0"
          >({{ urlList.length }})</text
        >
      </view>

      <view class="list-container" v-if="urlList.length > 0">
        <view class="file-item" v-for="item in urlList" :key="item.createTime">
          <view class="item-content">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-date">{{ formatDate(item.createTime) }}</text>
          </view>
          <view class="operator-box">
            <text class="item-icon" @click="selectAgent(item)">查看</text>
            <text class="item-icon item-icon-delete" @click="deleteAgent(item)"
              >删除</text
            >
          </view>
        </view>
      </view>

      <view class="empty-list" v-else>
        <text class="empty-text">暂无配置，请上传配置文件</text>
      </view>
    </view>

    <!-- 弹窗，让用户输入智能体名称和授权码 -->
    <view class="dialog" v-if="showDialog">
      <view class="dialog-content">
        <text class="dialog-title">添加智能体</text>
        <view class="dialog-input">
          <text class="input-label">智能体名称</text>
          <input
            class="input-field"
            v-model="formData.name"
            placeholder="请输入智能体名称"
          />
        </view>
        <view class="dialog-input">
          <text class="input-label">授权码</text>
          <input
            class="input-field"
            v-model="formData.agentKey"
            placeholder="请输入授权码"
          />
        </view>
        <view class="dialog-buttons">
          <button class="btn" @click="addAgent">添加</button>
          <button class="btn btn-cancel" @click="closeDialog">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import chooseFile from '@/pages/Setup/chooseFile.js'

export default {
  data() {
    return {
      urlList: [],
      showDialog: false,
      formData: {
        name: '',
        agentKey: '',
      },
      uploadJson: {},
      locationUrlItem: null,
    }
  },
  onShow: function () {
    this.urlList = uni.getStorageSync('urlList') || []
    this.locationUrlItem = uni.getStorageSync('locationUrlItem')
  },

  methods: {
    readFile(res) {
      console.log('文件内容', res.jsonData)
      
      this.uploadJson = res.jsonData
      console.log(' this.uploadJson', this.uploadJson)

      // 校验文件内容
      if (
        !this.uploadJson ||
        !this.uploadJson.name ||
        !this.uploadJson.agentKey ||
        !this.uploadJson.url
      ) {
        uni.showToast({
          title: '文件格式错误',
          icon: 'none',
        })
        return
      }

      this.formData.name = this.uploadJson.name
      this.formData.agentKey = ''
      this.showDialog = true
    },
    uploadFile() {
      plus.io.chooseFile(
        {
          title: '选择文件',
          filetypes: ['json'], // 允许的文件类型
          multiple: false, // 是否允许多选
        },
        async (res) => {
          console.log(res)
          const filePath = `file://${res.files[0]}`
          console.log('filePath', filePath)
          const appFilePath = plus.io.convertLocalFileSystemURL('_doc/') // app所在目录

          // 校验文件后缀
          if (!filePath.endsWith('.json')) {
            uni.showToast({
              title: '文件格式错误',
              icon: 'none',
            })
            return
          }

          const json = await chooseFile(filePath)
          this.uploadJson = JSON.parse(json)
          console.log(' this.uploadJson', this.uploadJson)

          // 校验文件内容
          if (
            !this.uploadJson.name ||
            !this.uploadJson.agentKey ||
            !this.uploadJson.url
          ) {
            uni.showToast({
              title: '文件格式错误',
              icon: 'none',
            })
            return
          }

          this.formData.name = this.uploadJson.name
          this.formData.agentKey = ''
          this.showDialog = true
        }
      )
    },
    closeDialog() {
      this.showDialog = false
    },
    setFile(json) {
      this.urlList.push({
        url: json.url,
        name: json.name,
        createTime: new Date().getTime(),
      })
      uni.setStorageSync('urlList', this.urlList)

      this.selectAgent(this.urlList[this.urlList.length - 1])
    },
    gotoHome() {
      uni.switchTab({
        url: '/pages/Home/index',
        success: () => {
          console.log('切换到 Home 页面')
        },
        fail: (error) => {
          console.log('切换失败', error)
        },
      })
    },
    selectAgent(item) {
      uni.setStorageSync('locationUrlItem', item)
      this.gotoHome()
    },
    formatDate(timestamp) {
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        '0'
      )}-${String(date.getDate()).padStart(2, '0')}`
    },
    addAgent() {
      if (!this.formData.name || !this.formData.agentKey) {
        uni.showToast({
          title: '请输入智能体名称和授权码',
          icon: 'none',
        })
        return
      }

      if (this.formData.agentKey === this.uploadJson.agentKey) {
        this.uploadJson.name = this.formData.name
        this.setFile(this.uploadJson)
        this.closeDialog()
      } else {
        uni.showToast({
          title: '授权码错误',
          icon: 'none',
        })
      }
    },
    deleteAgent(item) {
      uni.showModal({
        title: '确认删除',
        content: `是否删除智能体 ${item.name}？`,
        success: (res) => {
          if (res.confirm) {
            if (this.locationUrlItem.createTime === item.createTime) {
              this.locationUrlItem = null
              uni.setStorageSync('locationUrlItem', null)
            }
            this.urlList = this.urlList.filter((i) => i !== item)
            uni.setStorageSync('urlList', this.urlList)
          }
        },
      })
    },
  },
}
</script>

<style scoped lang="scss">
.content {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  padding: 20px;
}

.header {
  margin-bottom: 30px;

  .title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
}

.upload-section {
  margin-bottom: 30px;

  .upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #007aff;
    color: white;
    border-radius: 8px;
    height: 50px;
    box-shadow: 0 2px 6px rgba(0, 122, 255, 0.2);

    .btn-icon {
      font-size: 20px;
      margin-right: 8px;
    }

    .btn-text {
      font-size: 16px;
    }
  }
}

.list-section {
  flex: 1;
  display: flex;
  flex-direction: column;

  .list-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .list-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }

    .list-count {
      font-size: 14px;
      color: #666;
      margin-left: 8px;
    }
  }

  .list-container {
    flex: 1;
    overflow: auto;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .file-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px;
      border-bottom: 1px solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .item-content {
        display: flex;
        flex-direction: column;
      }

      .item-name {
        font-size: 16px;
        color: #333;
        margin-bottom: 5px;
      }

      .item-date {
        font-size: 12px;
        color: #999;
      }
      .operator-box {
        display: flex;
        .item-icon {
          font-size: 14px;
          color: #999;
          + .item-icon {
            margin-left: 4px;
          }
        }
        .item-icon-delete {
          color: #ff4444;
        }
      }
    }
  }

  .empty-list {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .empty-text {
      font-size: 14px;
      color: #999;
    }
  }
}

.load-more {
  height: 30px;
  width: 100%;
  text-align: center;
  color: #999;
  font-size: 12px;
  line-height: 30px;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  width: 80%;
  max-width: 400px;
  .dialog-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
  }
  .dialog-input {
    margin-bottom: 15px;
    .input-label {
      font-size: 14px;
      color: #333;
      margin-bottom: 5px;
    }
    .input-field {
      height: 40px;
      border: 1px solid #ccc;
      border-radius: 8px;
      padding: 0 10px;
      font-size: 16px;
      color: #333;
    }
  }
  .dialog-buttons {
    display: flex;
    .btn {
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      border-radius: 8px;
      font-size: 16px;
      color: #fff;
      background-color: #007aff;
      box-shadow: 0 2px 6px rgba(0, 122, 255, 0.2);
      /* &:first-child {
        margin-right: 10px;
      } */
    }
    .btn-cancel {
      background-color: #999;
    }
  }
}
</style>
